package com.yuehuanghun.admin.generator.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import com.yuehuanghun.admin.generator.config.GenConfig;
import com.yuehuanghun.framework.util.StringUtils;
import lombok.Data;

/**
 * 用于生成代码的Table对象.对应数据库的table
 */
@Data
public class Table {
	private String jdbcName;
	private String remarks;
	private String className;
	private String tableComments;
	private Date createTime; //表创建日期 
	private Date updateTime; //表更新日期
	/** 同义词表（如果是）的拥有者 */
	private String ownerSynonymName = null;
	private Collection<Column> columns = new LinkedHashSet<Column>();
	private List<String> primaryKeyColumns = new ArrayList<>();
	private List<Index> indexs = new ArrayList<Index>();

	public String getTableComments() {
		if (StringUtils.isNotBlank(tableComments))
			return tableComments;
		return StringUtils.defaultIfBlank(getRemarks(), getClassName());
	}

	public static String removeTableSqlNamePrefix(String sqlName) {
		String prefixs = GenConfig.getTablePrefix();
		if (StringUtils.isBlank(prefixs) || !GenConfig.autoRemovePre) {
			return sqlName;
		}
		for (String prefix : prefixs.split(",")) {
			String removedPrefixSqlName = sqlName.startsWith(prefix) ? sqlName.substring(prefix.length()) : sqlName;
			if (!removedPrefixSqlName.equals(sqlName)) {
				return removedPrefixSqlName;
			}
		}
		return sqlName;
	}

	public void addColumn(Column column) {
		columns.add(column);
	}

	/**
	 * 根据sqlName得到的类名称，示例值: UserInfo
	 * 
	 * @return
	 */
	public String getClassName() {
		if (StringUtils.isBlank(className)) {
			String removedPrefixSqlName = removeTableSqlNamePrefix(jdbcName);
			className = StringUtils.convertToCamelCase(removedPrefixSqlName.matches("^[_A-Z]+$") ? removedPrefixSqlName.toLowerCase() : removedPrefixSqlName);
		}
		return className;
	}

	public String getFieldName() {
		return className.substring(0, 1).toLowerCase() + className.substring(1);
	}

	public String toString() {
		return "Database Table:" + getJdbcName() + " to ClassName:" + getClassName();
	}
}
